package com.vviton.zyhj.common.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.vviton.zyhj.common.utils.LocaleUtil;
import com.vviton.zyhj.common.utils.WebUtils;

/**
 * 语言过滤器
 */
public class I18nFilter implements Filter {

    /** 语言key */
    private String langCookie = "language";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 获取cookie
        String locale = WebUtils.getCookie((HttpServletRequest) request, langCookie);
        if (locale == null || "".equals(locale)) {
            locale = "zh";
        }
        Locale newLocale = Locale.SIMPLIFIED_CHINESE;
        if ("en".equals(locale)) {
            newLocale = Locale.ENGLISH;
        } else if ("zh".equals(locale)) {
            newLocale = Locale.SIMPLIFIED_CHINESE;
        }
        LocaleUtil.setLocale(newLocale);
        // 设置语言
        /*request.setAttribute("lang", LocaleUtil.getLocale().getLanguage());
        request.setAttribute("i18n", MessageSource.getInstance().getMessages(LocaleUtil.getLocale()));*/

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        this.langCookie = filterConfig.getInitParameter("langCookie");

    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}
